package com.shawn.baseappbygroovydsl.utils

import android.content.Context
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import com.shawn.baseappbygroovydsl.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.InputStreamReader
import java.util.LinkedList
import java.util.Random

/**
 * @author Secret
 * @since 2023/8/17
 */
object UtilHundredContribute {

    private var index = 0
    private val contentList = LinkedList<String>()
    private val termForegroundColorSpan =
        ForegroundColorSpan(Color.parseColor("#FDA551"))
    private val random = Random()
    private val span = SpannableStringBuilder()
    private val str1 = "轻松提现了"

    private val icon = arrayListOf<Int>(
        R.mipmap.a1,
        R.mipmap.a2,
        R.mipmap.a3,
        R.mipmap.a4,
        R.mipmap.a5,
        R.mipmap.a6,
    )

    suspend fun initPresentTxt(context: Context) {
        if (contentList.isEmpty()) {
            withContext(Dispatchers.IO) {
                InputStreamReader(context.resources.openRawResource(R.raw.hundred_contribute)).use {
                    it.readLines().forEach { content ->
                        contentList.add(content)
                    }
                }
            }
        }
    }

    fun curIcon(): Int {
        if (index < icon.size) {
            return icon[index]
        }
        return icon[icon.size - 1]
    }

    fun curPresentTxt(): SpannableStringBuilder {
        span.clear()
        if (index >= contentList.size) {
            index = 0
        }
        val value = contentList[index]
        index++
        val temp = value.split("_")
        val nameTemp = temp[0]
        val name = if (nameTemp.length > 4) {
            "%s...".format(nameTemp.substring(0, 4))
        } else {
            nameTemp
        }
        val money = "100元"

        val time = random.nextInt(49) + 1
        val str2 = if (time > 24) {
            val day = random.nextInt(3) + 1
            "%d天前".format(day)
        } else {
            "%d小时前".format(time)
        }

        span.append(name)
        span.append(str1)
        span.append(money)
        span.append("  ")
        span.append(str2)
        span.setSpan(
            termForegroundColorSpan,
            name.length + str1.length,
            name.length + str1.length + money.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        return span
    }

}